angular.module('projectUpdate', ['ui.grid', 'ui.grid.selection', 'ui.select', 'ui.grid.pagination',
        'ui.grid.resizeColumns', 'ui.grid.moveColumns', 'toastr', 'common'])
    .controller('projectUpdateController',
        ['$scope', '$http', '$compile', 'toastr', 'commonService',
            function ($scope, $http, $compile, toastr) {
                var start = new Date($("#start").attr('value'));
                var end = new Date($("#end").attr('value'));
                var members = {};
                var complete_leader = [];
                var count = 0;
                var project = function () {
                    this.p_name = '新项目';
                    this.pm = '';
                    this.leader = '';
                    this.status = 'established';
                    this.start_date = new Date().Format('yyyy/MM/dd');
                    this.end_date = new Date().Format('yyyy/MM/dd');
                    this.uniqueId = ++count;
                };
                $scope.statusMap = [];

                var tempProject = new project();
                $scope.addList = {1: tempProject};

                if (!!$.cookie("toast")) {
                    toastr.success($.cookie("toast"));
                    $.cookie("toast", "",{path : "/project"});
                }

                function validateUnique(value, schema, attr, cb) {
                    console.log(value);
                    console.log($scope.addList);
                    $http.post('/validate/unique', {value: value, schema: schema, attr: attr}).success(function (data) {
                        if (data === 'success') {
                            cb(true);
                        } else if (data === 'fail') {
                            cb(false);
                        } else {
                            toastr.error("服务器出错");
                        }
                    });
                }

                $("#pname").on('blur', function () {
                    validateUnique("'" + $("#pname").val() + "'", "project", "p_name", function (result) {
                        !result && toastr.warning("该项目名称已存在");
                    });
                });

                if ($("#operation").val() === 'batchAdd') {
                    $scope.query = $scope.addList[1];
                } else {
                    $scope.query = {
                        p_name: $("#pname").attr('value'),
                        pm: $("#pm").attr('value'),
                        leader: $("#leader").attr('value'),
                        status: $("#status").val(),
                        start_date: start.Format('yyyy/MM/dd'),
                        end_date: end.Format('yyyy/MM/dd'),
                        id: $("#pid").html()
                    };
                }

                $scope.back = function () {
                    window.history.back();
                };

                $scope.edit = function (event) {
                    $(".active").removeClass('active');
                    $(event.target).addClass('active');
                    $http.post('/project/find', {id: parseInt($(event.target).attr('id').split('-')[1])}).success(function (data) {
                        $scope.query = {
                            p_name: data[0].p_name,
                            pm: data[0].project_pm,
                            leader: data[0].project_leader,
                            status: data[0].status,
                            start_date: new Date(data[0].start_date).Format('yyyy/MM/dd'),
                            end_date: new Date(data[0].end_date).Format('yyyy/MM/dd'),
                            id: data[0].p_id
                        };
                        $("#date-start_date").val($scope.query.start_date);
                        $("#date-end_date").val($scope.query.end_date);
                    }).error(function () {
                        toastr.error('请检查网络连接');
                    });

                };

                $scope.editList = function (id) {
                    $(".active").removeClass('active');
                    $("#p-list-" + id).addClass('active');
                    $scope.query = $scope.addList[id];
                    $("#date-start_date").val(new Date($scope.query.start_date).Format('yyyy/MM/dd'));
                    $("#date-end_date").val(new Date($scope.query.end_date).Format('yyyy/MM/dd'));
                };

                $scope.add = function () {
                    if (new Date($scope.query.start_date).valueOf() > new Date($scope.query.end_date).valueOf()) {
                        toastr.warning('开始时间不能晚于结束时间');
                        return;
                    }

                    if($scope.query.p_name == "新项目") {
                        toastr.warning("请修改项目名");
                        return;
                    }

                    $scope.query.pm = $("#pm").val();
                    $scope.query.leader = $("#leader").val();
                    $scope.query.project_pm = parseInt(members[$scope.query.pm]);
                    $scope.query.project_leader = parseInt(members[$scope.query.leader]);
                    if (!$scope.query.project_pm || !$scope.query.project_leader || !$scope.query.p_name) {
                        toastr.warning('输入信息不完整或有误');
                        return;
                    }

                    $scope.addList[$scope.query.uniqueId] = $.extend({}, $scope.query);
                    $scope.query = new project();
                    $scope.addList[$scope.query.uniqueId] = $scope.query;

                    $(".active").removeClass('active');

                    var template = angular.element('<li id="p-list-' + $scope.query.uniqueId + '" class="list-group-item active" ng-click="editList(' +
                        $scope.query.uniqueId + ')"><i class="fa fa-trash-o remove-icon" ng-click="minus(' +
                        $scope.query.uniqueId + ')"></i>&nbsp;<span ng-bind="addList[' + $scope.query.uniqueId +
                        '].p_name"></span></li>');
                    var compiled = $compile(template)($scope);
                    angular.element("#pList").append(compiled);
                    $scope.addList[$scope.query.uniqueId].element = compiled;
                    $("#date-start_date").val(new Date($scope.query.start_date).Format('yyyy/MM/dd'));
                    $("#date-end_date").val(new Date($scope.query.end_date).Format('yyyy/MM/dd'));
                };

                $scope.minus = function (id) {
                    window.tempId = id;
                    $(".remove-prj").modal();
                    $("#ensure-remove").on("click", function (event) {
                        $scope.addList[window.tempId].element.remove();
                        findPrevious();
                        $scope.addList[window.tempId] = null;
                        $(".remove-prj").modal('hide');
                    });
                };

                $scope.remove = function () {
                    if ($scope.query.element) {
                        $scope.query.element.remove();
                        var tempId = $scope.query.uniqueId;
                        findPrevious();
                        $scope.addList[tempId] = null;
                    } else {
                        toastr.warning("不能移除第一项");
                    }
                };

                function findPrevious() {
                    var tempId = $scope.query.uniqueId;
                    if ($scope.addList[tempId - 1]) {
                        $scope.query = $scope.addList[tempId - 1];
                        if ($(".active").length == 0) {
                            $("#p-list-" + (tempId - 1)).addClass('active');
                        }
                    } else {
                        $scope.query.uniqueId--;
                        findPrevious();
                    }
                }

                $scope.saveAll = function () {
                    var postArray = [];
                    for (var i in $scope.addList) {
                        if (!!$scope.addList[i]) {
                            $scope.addList[i].project_pm = members[$scope.addList[i].pm];
                            $scope.addList[i].project_leader = members[$scope.addList[i].leader];
                            if (!$scope.addList[i].project_pm || !$scope.addList[i].project_leader) {
                                toastr.warning('输入不完整,请确认输入');
                                return;
                            }
                            postArray.push($scope.addList[i]);
                        }
                    }
                    var items = 0;
                    for (var j in $scope.addList) {
                        items++;
                    }
                    if (items == 1) {
                        $scope.save();
                        return;
                    } else {
                        $http.post('/project/add', postArray).success(function (data) {
                            if (data === 'success') {
                                $.cookie("toast", "全部保存成功",{path : '/project'});
                                window.location.href = window.location.href;
                            } else {
                                toastr.error(data.description);
                            }
                        }).error(function () {
                            toastr.error('请检查网络连接');
                        });
                    }
                };

                $scope.save = function () {
                    if (new Date($scope.query.start_date).valueOf() > new Date($scope.query.end_date).valueOf()) {
                        toastr.warning('开始时间不能晚于结束时间');
                        return;
                    }
                    $scope.query.pm = $("#pm").val();
                    $scope.query.leader = $("#leader").val();
                    $scope.query.start_date = new Date($scope.query.start_date).Format('yyyy-MM-dd');
                    $scope.query.end_date = new Date($scope.query.end_date).Format('yyyy-MM-dd');
                    $scope.query.project_pm = parseInt(members[$scope.query.pm]);
                    $scope.query.project_leader = parseInt(members[$scope.query.leader]);
                    $scope.query.id = parseInt($scope.query.id);
                    var url;
                    $scope.query.id ? (url = 'save') : (url = 'add');

                    if (!$scope.query.project_pm || !$scope.query.project_leader || !$scope.query.p_name) {
                        toastr.warning('输入不完整或信息有误');
                        return;
                    }
                    $http.post('/project/' + url, $scope.query).success(function (data) {
                        if (data === 'success') {
                            $.cookie("toast", "保存成功",{path : '/project'});
                            if ($("#operation").val() === 'batchAdd') {
                                window.location.href = window.location.href;
                            } else {
                                if (window.parent) {
                                    window.parent.location.href = window.parent.location.href;
                                } else {
                                    window.location.href = window.location.href;
                                }
                            }
                        } else {
                            toastr.error(data.description);
                        }
                    }).error(function () {
                        toastr.error('请检查网络连接');
                    });
                };

                $http.get('/user/mapping').success(function (data) {
                    $scope.statusMap = data.statusKey;
                    for (var i in data.role) {
                        if (data.role[i] !== 'admin') {
                            members[data.name[i]] = i;
                            complete_leader.push(data.name[i]);
                        }
                    }

                    $("#pm").autocomplete({
                        source: complete_leader,
                        select: function (event, ui) {
                            $scope.query.pm = ui.item.value;
                        }
                    });
                    $("#leader").autocomplete({
                        source: complete_leader,
                        select: function (event, ui) {
                            $scope.query.leader = ui.item.value;
                        }
                    });
                });

                $scope.closeModal = function () {
                    $(".modal-add", window.parent.document).css('display', 'none');
                    $("#modal-c", window.parent.document).css('z-index', '-1');
                    $("#modal-i", window.parent.document).css('z-index', '-1');
                };

                $("#start_cancel").click(function () {
                    $scope.query.start_date = '';
                    $("#date-start_date").val('');
                });

                $("#end_cancel").click(function () {
                    $("#date-end_date").val('');
                });
            }
        ]);